//
//  SKYInfoServer.m
//  SkyonSDK
//
//  Created by 张二帅 on 2018/5/10.
//  Copyright © 2018年 Skyon. All rights reserved.
//

#import "SKYInfoServer.h"
#import "SKYEventAttemperEngine.h"
#import "SKYInfoAcquisitionInterface.h"
#import "KSCrash.h"
#import "SKYPageTrackerMonitor.h"
#import "SKYBattery.h"
#import "SKYDevice.h"
#import "SKYModel.h"
#import "SKYCPUFrequency.h"

/** 当前cpu频率 */
NSString const* kSKYCurrentCPUFrequency = @"";
/** 当前电池电量 */
NSString const* kSKYCurrentBatteryLevel = @"";
/** 当前电池是否在充电 */
NSString const* kSKYCurrentBatteryCharging = @"";
/** 当前后台进程情况 */
NSString const* kSKYCurrentBackProcess = @"";

/**
 崩溃时指定信息采集

 @param writer 写入采集对象
 */
static void sky_advanced_crash_callback (const KSCrashReportWriter *writer) {
    writer->addStringElement(writer,"currentPage",[kSKYCurrentPageName cStringUsingEncoding:NSUTF8StringEncoding]);
    writer->addStringElement(writer,"currentPageStartTime",[kSKYCurrentPageStartTime cStringUsingEncoding:NSUTF8StringEncoding]);
    writer->addStringElement(writer,"cpuFrequency",[kSKYCurrentCPUFrequency cStringUsingEncoding:NSUTF8StringEncoding]);
    writer->addStringElement(writer,"batteryLevel",[kSKYCurrentBatteryLevel cStringUsingEncoding:NSUTF8StringEncoding]);
    writer->addStringElement(writer,"batteryIsCharging",[kSKYCurrentBatteryCharging cStringUsingEncoding:NSUTF8StringEncoding]);
    writer->addStringElement(writer,"backProcess",[kSKYCurrentBackProcess cStringUsingEncoding:NSUTF8StringEncoding]);
}


/** 若开启定期循环采集，默认发送间隔 */
int kSKYRegularReportDefaultSecond = 60;
/** 初次调用SDK采集模块，标识key */
NSString *const kSKYFirstInstallInfoAcquisitionKey = @"com.Skyon.firstInstallInfoAcquisition";
/** 定期采集模块，事件循环key */
NSString *const kSKYRegularInfoAcquisitionEventKey = @"com.Skyon.regularInfoAcquisitionEvent";
/** 定期更新崩溃采集信息事件循环key */
NSString *const kSKYRegularCrashInfoUpdateEventKey = @"com.Skyon.regularCrashInfoUpdateEvent";
/** 定期更新CPU频率事件循环key */
NSString *const kSKYRegularCPUFrequencyUpdateEventKey = @"com.Skyon.regularCPUFrequencyUpdateEvent";

@interface SKYInfoServer()
/** 应用配置 */
@property (nonatomic, strong, readwrite) SKYAnalyticsConfig *config;
/** 当前网络ip */
@property (nonatomic, copy, readwrite, nullable) NSString *netIp;
@end

/** 时间格式化对象 */
static NSDateFormatter *sky_dateFormatter;
@implementation SKYInfoServer

- (instancetype)init
{
    self = [super init];
    if (self) {
        _logEnabled = NO;
        _regularReportSecond = kSKYRegularReportDefaultSecond;
        sky_dateFormatter = [[NSDateFormatter alloc] init];
        [sky_dateFormatter setDateFormat:@"yyyy-MM-dd,HH:mm:ss"];
        _infoAcquisitionURLString = @"http://mcms.fsc.tp95589.com/TX0B004";
    }
    return self;
}

#pragma mark - methods

SKY_DEF_SINGLETON(SKYInfoServer)


#pragma mark - propertys
- (void)setRegularReportSecond:(int)regularReportSecond {
    if (regularReportSecond <= 0) {
        _regularReportSecond = kSKYRegularReportDefaultSecond;
    } else {
        _regularReportSecond = regularReportSecond;
    }
    if ([SKYInfoServer sharedInstance].netIp != nil) {
        [SKYInfoServer startRegularInfoAcquisition];
    }
}

#pragma mark - public class methods

+ (void)startInfoServerWithConfigure:(SKYAnalyticsConfig *)configure;{
    [SKYInfoServer sharedInstance].config = configure;
    [SKYInfoServer startRegularCrashInfoUpdate];
    [SKYInfoServer startRegularCPUFrequency];
    [SKYInfoAcquisitionInterface getNetIpCompletion:^(NSString * _Nullable netIp) {
        [SKYInfoServer sharedInstance].netIp = netIp == nil ? @"" : netIp;
        // 1、调用初次采集模块、2、调用启动采集模块  3、调用定期循环采集模块
        [SKYInfoServer startFirstInstallInfoAcquisition];
        [SKYInfoServer startAppLaunchInfoAcquisition];
        [SKYInfoServer startRegularInfoAcquisition];
    }];
    
}

/**
 格式化时间对象
 
 @param date 时间对象
 @return 格式化后字符串
 */
+ (NSString *)stringFromDate:(NSDate *)date {
    if (date == nil) {
        return nil;
    }
    return [sky_dateFormatter stringFromDate:date];
}

#pragma mark - class methods
/**
 开启初次安装采集模块
 */
+ (void)startFirstInstallInfoAcquisition {
    id value = [[NSUserDefaults standardUserDefaults] valueForKey:kSKYFirstInstallInfoAcquisitionKey];
    if (value == nil) {
        [[NSUserDefaults standardUserDefaults] setValue:@(YES) forKey:kSKYFirstInstallInfoAcquisitionKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        //采集指定信息，上传
        [SKYInfoAcquisitionInterface sendFistInstallInfo];
    }
}

/**
 开启启动采集模块
 */
+ (void)startAppLaunchInfoAcquisition {
    [SKYInfoAcquisitionInterface sendAppLaunchInfo];
    if (![SKYInfoServer sharedInstance].config.bCrashReportEnabled) {
        return;
    }
    [[KSCrash sharedInstance] install];
    [KSCrash sharedInstance].onCrash = sky_advanced_crash_callback;
    NSArray *array = [[KSCrash sharedInstance] reportIDs];
    //遍历拿到最新的崩溃日志
    __block NSDictionary *crashDict = nil;
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = [[KSCrash sharedInstance] reportWithID:obj];
        crashDict = dict;
        [[KSCrash sharedInstance] deleteReportWithID:obj];
    }];
    if (crashDict) {
        [SKYInfoAcquisitionInterface sendCrashInfo:crashDict];
    }
}

/**
 开启定期循环采集模块
 */
+ (void)startRegularInfoAcquisition {
    if ([SKYInfoServer sharedInstance].config.regularReportPolicy == SKYRegularReport_Close) {
        return;
    }
    int timer = [SKYInfoServer sharedInstance].config.regularReportPolicy == SKYRegularReport_Open ? kSKYRegularReportDefaultSecond : [SKYInfoServer sharedInstance].regularReportSecond;
    [[SKYEventAttemperEngine sharedInstance] registerAction:^{
        //采集指定信息，上传
        [SKYInfoAcquisitionInterface sendRegularInfo];
    } timer:timer name:kSKYRegularInfoAcquisitionEventKey];
}

/**
 定期更新自定义崩溃信息，更新频率为10s
 */
+ (void)startRegularCrashInfoUpdate {
    if (![SKYInfoServer sharedInstance].config.bCrashReportEnabled) {
        return;
    }
    [SKYInfoServer updateCustomCrashInfo];
    [[SKYEventAttemperEngine sharedInstance] registerAction:^{
        [SKYInfoServer updateCustomCrashInfo];
    } timer:10 name:kSKYRegularCrashInfoUpdateEventKey];
}
/**
 更新自定义崩溃信息
 */
+ (void)updateCustomCrashInfo {
    kSKYCurrentBatteryLevel = [UIDevice currentDevice].batteryMonitoringEnabled ? [SKYBattery getBatteryLevel] : kSKYCurrentBatteryLevel;
    kSKYCurrentBatteryCharging = [UIDevice currentDevice].batteryMonitoringEnabled ? [NSString stringWithFormat:@"%@",[NSNumber numberWithBool:[SKYBattery batteryIsCharging]]] : kSKYCurrentBatteryCharging;
    NSArray *processArray = [SKYDevice runningProcesses];
    kSKYCurrentBackProcess = (processArray != nil && processArray.count > 0) ? [processArray SKY_modelToJSONString] : kSKYCurrentBackProcess;
}
/**
 定期更新CPU频率，暂定每10分钟更新一次
 */
+ (void)startRegularCPUFrequency {
#if TARGET_IPHONE_SIMULATOR
    
#else
    kSKYCurrentCPUFrequency = [SKYCPUFrequency cpuFrequencyKHZ];
    [[SKYEventAttemperEngine sharedInstance] registerAction:^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            kSKYCurrentCPUFrequency = [SKYCPUFrequency cpuFrequencyKHZ];
        });
    } timer:60*10 name:kSKYRegularCPUFrequencyUpdateEventKey];
#endif
}



@end
